package com.py.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.py.model.common.dtos.ResponseResult;
import com.py.model.search.dtos.UserSearchDto;
import com.py.model.user.pojos.ApUser;
import com.py.search.service.ApUserSearchService;
import com.py.search.service.ArticleSearchService;
import com.py.utils.common.ApUserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    private RestHighLevelClient highLevelClient;
    @Autowired
    private ApUserSearchService apUserSearchService;


    /**
     * 文章搜索
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) {
        //判断
        if (StringUtils.isEmpty(dto.getSearchWords())) {
            log.info("关键字数据为空");
            return ResponseResult.okResult(null);
        }
        SearchRequest searchRequest = new SearchRequest("app_info_article");

        //布尔查询，组装多个条件
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //构造查询条件 根据关键字分词查询 查询文章 或 标题是否包含
        QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders.queryStringQuery(dto.getSearchWords())
                .field("title").field("content")
                .defaultOperator(Operator.OR);
        boolQueryBuilder.must(queryStringQueryBuilder);

        ApUser user = ApUserThreadLocalUtil.get();
        //用户没有登录并且不是首次加载则不能保存
        if(user != null && dto.getFromIndex() == 0){
            //异步保存，用户搜索记录
            apUserSearchService.insert(dto.getSearchWords(),user.getId());
        }
        //范围查询条件
        RangeQueryBuilder publishTime = QueryBuilders.rangeQuery("publishTime")
                .lt(dto.getMinBehotTime());
        boolQueryBuilder.filter(publishTime);

        //分页
        searchRequest.source().query(boolQueryBuilder)
                .from(dto.getFromIndex()) //当前起始位置
                .size(dto.getPageSize()) //当前页条数
                .sort("publishTime", SortOrder.DESC);//排序
        //高亮
        searchRequest.source().highlighter(new HighlightBuilder()
                .field("title")
                .preTags("<font style='color: red; font-size: inherit;'>")
                .postTags("</font>"));

        try {
            SearchResponse response = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            //结果（正常的结果+高亮结果）
            List<Map> result = new ArrayList<>();
            SearchHits hits = response.getHits();
            for (SearchHit hit : hits) {
                Map map = JSON.parseObject(hit.getSourceAsString(), Map.class);

                //获取高亮结果
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (highlightFields == null || highlightFields.size() == 0) {
                    log.info("没有高亮数据");
                    map.put("h_title",map.get("title"));
                }else {
                    HighlightField title = highlightFields.get("title");
                    Text[] fragments = title.getFragments();
                    String join = org.apache.commons.lang.StringUtils.join(fragments);
                    map.put("h_title",join);
                }
                result.add(map);
            }
                //返回数据
                return ResponseResult.okResult(result);
        } catch (IOException e) {
            log.error("查询异常-->{}", e);
            return ResponseResult.okResult(null);
        }
    }
}